/**
 * Copyright (C), 2001-2023, www.bosssof.com.cn
 * FileName: GatewayEntryHandler
 * Author: Administrator
 * Date: 2023-04-17 15:33:31
 * Description:
 * <p>
 * History:
 * <author> Administrator
 * <time> 2023-04-17 15:33:31
 * <version> 1.0.0
 * <desc> 版本描述
 */
package com.sd365.gateway.core.handler;

import com.alibaba.fastjson.JSONObject;

import com.sd365.common.util.JwtTokenBuilder;
import com.sd365.common.util.TokenUtil;
import com.sd365.gateway.core.config.CustomFilters;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: GatewayEntryHandler
 * @Description: 负责网关的请求的守护和分发
 *  主要包含 1、黑名单检测 2、token合法性判断 3、请求转发
 * @Author: Administrator
 * @Date: 2023-04-17 15:33
 **/
@Slf4j
@Component
public class GatewayEntryHandler implements IGatewayEntryHandler{
    /**
     * 密码
     */
    private String secret = "$6$0123$";
    /**
     * nacos 配置文件中配置的客户指定放行的过滤器
     */
    @Autowired
    private CustomFilters customFilters;
    /**
     * 网关服务地址
     */
    public static final String AUTHORIZATION_URL = "http://gateway-authorization";

    /**
     * 创建对象的时候包含了ribbon功能
     */
    @Resource
    private RestTemplate restTemplate;
    @Override
    public boolean detectConfigWhiteList(String URI) {
        /**
         * 某一些请求接口允许
         */
        if (!CollectionUtils.isEmpty(customFilters.getFilters())) {
            List<String> whiteList=customFilters.getFilters();
            for (String white : whiteList) {
                if (URI.contains(white)) {
                    return true;
                }
            }
            return false;
        } else {return false;}
    }

    @Override
    public boolean detectCommonResource(String URI) {
        try {
            return  restTemplate.getForObject(AUTHORIZATION_URL + "/v1/common/resource?&url=" + URI, Boolean.class);
        }catch (Exception ex){
            log.error("detectCommonResource 访问redis发生错误",ex);
            return false;
        }

    }
    /**
     * 分割token并检验签名
     * 普通做法为
     * String[] strings = token.split("//.");
     * jwtTokenBuilder.buildHead(JSONObject.parseObject(strings[0]));
     * jwtTokenBuilder.buildPayload(JSONObject.parseObject(strings[1]));
     * return jwtTokenBuilder.verifySignature(strings[2],"$6$bosssoft$");
     * @author  Hejiale
     */
    @Override
    public boolean verifySign(String token) {
        List<String> list = TokenUtil.parseToken(token);
        String head = list.get(0), payLoad = list.get(1), signature = list.get(2);
        JwtTokenBuilder jwtTokenBuilder = new JwtTokenBuilder();
        String realSignature = jwtTokenBuilder.getSignature(head, payLoad,secret);
//        System.out.println("realSignature: "+realSignature);
//        System.out.println("signature: "+signature);
        return signature.equals(realSignature);

//        String[] strings = token.split("//.");
//        JwtTokenBuilder jwtTokenBuilder = new JwtTokenBuilder();
//      jwtTokenBuilder.buildHead(JSONObject.parseObject(strings[0]));
//      jwtTokenBuilder.buildPayload(JSONObject.parseObject(strings[1]));
//      return jwtTokenBuilder.verifySignature(strings[2],"$6$bosssoft$");
    }

    @Override
    public Integer dispatch2Authorize(String token, String uri) {
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put("token",token);
        paramMap.put("api",uri);
        return restTemplate.getForObject(AUTHORIZATION_URL + "/v1/authorization?token={token}&api={api}", Integer.class,paramMap);
    }
}
